package com.gla.market.fragments;

import static android.support.v4.content.ContextCompat.checkSelfPermission;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.gla.market.R;
import com.gla.market.constant.Constants;
import com.gla.market.entity.FYH_Shop;
import com.gla.market.utils.NetUtil;
import com.tencent.lbssearch.TencentSearch;
import com.tencent.lbssearch.httpresponse.HttpResponseListener;
import com.tencent.lbssearch.object.param.DrivingParam;
import com.tencent.lbssearch.object.param.WalkingParam;
import com.tencent.lbssearch.object.result.DrivingResultObject;
import com.tencent.lbssearch.object.result.RoutePlanningObject;
import com.tencent.lbssearch.object.result.WalkingResultObject;
import com.tencent.map.geolocation.TencentLocation;
import com.tencent.map.geolocation.TencentLocationListener;
import com.tencent.map.geolocation.TencentLocationManager;
import com.tencent.map.geolocation.TencentLocationUtils;
import com.tencent.tencentmap.mapsdk.maps.CameraUpdateFactory;
import com.tencent.tencentmap.mapsdk.maps.TencentMap;
import com.tencent.tencentmap.mapsdk.maps.TextureMapView;
import com.tencent.tencentmap.mapsdk.maps.model.BitmapDescriptor;
import com.tencent.tencentmap.mapsdk.maps.model.BitmapDescriptorFactory;
import com.tencent.tencentmap.mapsdk.maps.model.IOverlay;
import com.tencent.tencentmap.mapsdk.maps.model.LatLng;
import com.tencent.tencentmap.mapsdk.maps.model.LatLngBounds;
import com.tencent.tencentmap.mapsdk.maps.model.Marker;
import com.tencent.tencentmap.mapsdk.maps.model.MarkerOptions;
import com.tencent.tencentmap.mapsdk.maps.model.PolylineOptions;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class Nearby extends Fragment implements TencentLocationListener {

    private LinearLayout parentView;
    private Context mContext;
    private TencentLocation nowLocation;
    private Marker now_marker;
    public static Boolean showNum = false;
    private TencentMap tencentMap;
    private TextureMapView mapView;
    private List<IOverlay> overlays = new ArrayList<>();
    private List<FYH_Shop> listShop = new ArrayList<>();
    private LatLng nowLatLng;
    private LatLng fromPoint; // 起点坐标
    private LatLng toPoint = new LatLng(39.232,116.323); //终点坐标
    private LatLng center;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_nearby, null);
        mContext = getContext();
        //初始化
        init(view);
        //获取定位权限
        requirePermission();
        //获取定位
        getLocation();
        return view;
    }

    private void init(View view){
        parentView = (LinearLayout)view.findViewById(R.id.shopcart_root);
        mapView = new TextureMapView(mContext);
        parentView.addView(mapView);
        tencentMap = mapView.getMap();

    }

    private void getPoint() {
        String url = Constants.BASE_URL + Constants.GET_FYH_SHOP_URL + Constants.GET_FYH_SHOPNEAR_URL + Constants.ulalo(nowLocation.getLatitude(),nowLocation.getLongitude());
        NetUtil.doGet(url, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e("调试", "错误信息：" + e.toString());
                        Message message = Message.obtain();
                        message.what = -1;
                        uiHandler.sendMessage(message);
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string().trim();
                        com.alibaba.fastjson.JSONObject object = JSON.parseObject(result);
                        Message message = Message.obtain();

                        if (!object.getString("message").contains("JWT") && object.getString("error")==null && object.getInteger("code")==100) {
                            JSONArray array = object.getJSONArray("data");
                            //获得商品list
                            listShop = JSONArray.parseArray(array.toString(), FYH_Shop.class);
                            message.what = 2;
                        } else {
                            message.what = 0;
                        }
                        uiHandler.sendMessage(message);
                    }
                }
        );
    }

    public void showPoint(){
        now_marker = tencentMap.addMarker(new MarkerOptions(nowLatLng));
        for(int i=0;i<listShop.size();i++){
            double rx = listShop.get(i).getLatitude();
            double ry = listShop.get(i).getLongitude();
            LatLng position = new LatLng(rx,ry);
            System.out.println(position);
            BitmapDescriptor custom = BitmapDescriptorFactory.fromResource(R.drawable.ic_shopcart_map);
            Marker mCustomMarker = tencentMap.addMarker(new MarkerOptions(position).icon(custom));
            mCustomMarker.setTag(listShop.get(i));
            mCustomMarker.setTitle(listShop.get(i).getName());
        }
        if(showNum) {
            Toast.makeText(mContext, "为您找到" + listShop.size() + "家附近5公里内宠物商店", Toast.LENGTH_SHORT).show();
            showNum = false;
        }

        tencentMap.setOnMarkerClickListener(new TencentMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                FYH_Shop shop = (FYH_Shop) marker.getTag();
                View contentView = LayoutInflater.from(mContext).inflate(R.layout.neayby_location_pop, null);
                PopupWindow popWnd = new PopupWindow (mContext);
                popWnd.setContentView(contentView);
                popWnd.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
                popWnd.setHeight(500);
                popWnd.setAnimationStyle(R.anim.nearby_pop_anim);
                popWnd.setTouchable(true);
                popWnd.setBackgroundDrawable(new BitmapDrawable());
                popWnd.setOutsideTouchable(true);

                Button bt_share = contentView.findViewById(R.id.nearby_share_button);
                Button bt_route = contentView.findViewById(R.id.neayby_route_button);
                Button bt_navigation = contentView.findViewById(R.id.neayby_navigation_button);
                bt_route.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        fromPoint = nowLatLng;
                        toPoint = new LatLng(shop.getLatitude(),shop.getLongitude());
                        center = new LatLng((fromPoint.getLatitude()+toPoint.getLatitude())/2, (fromPoint.getLongitude()+toPoint.getLongitude())/2);
                        //将两点加入要显示的范围点
                        overlays.clear();
                        overlays.add(now_marker);
                        overlays.add(marker);
                        getWalkingRoute();
                    }
                });
                TextView tv_shopName = contentView.findViewById(R.id.neayby_shop_name);tv_shopName.setText(shop.getName());
                TextView tv_shopIntro = contentView.findViewById(R.id.neayby_shop_introduction);tv_shopIntro.setText(shop.getIntroduction());
                TextView tv_address = contentView.findViewById(R.id.nearby_address);
                DecimalFormat df = new DecimalFormat(".0");
                tv_address.setText(
                        df.format(TencentLocationUtils.distanceBetween(shop.getLatitude(),shop.getLongitude(),nowLocation.getLatitude(),nowLocation.getLongitude()))
                        +"m   |   "+shop.getAddress());
                popWnd.showAtLocation(parentView, Gravity.TOP,0, 0);
                return false;
            }
        });
    }
    public void getLocation(){
        //获取定位
        TencentLocationManager mLocationManager = TencentLocationManager.getInstance(mContext);
        mLocationManager.requestSingleFreshLocation(null, this, Looper.getMainLooper());
    }

    @Override
    public void onLocationChanged(TencentLocation tencentLocation, int i, String s) {

        Log.d("调试",tencentLocation.toString()+"\n"+i+"\n"+s);
        nowLocation = tencentLocation;
        //添加一个地图中心点标注
        if (tencentMap == null || tencentMap.isDestroyed()){
            Log.d("调试","map为null ");
            return;
        }
        //获取宠物商店位置
        getPoint();

        //设置用户定位为地图中心点
        nowLatLng = new LatLng(nowLocation.getLatitude(),nowLocation.getLongitude());
        //把地图变换到指定的状态,生成一个把地图移动到指定的经纬度到屏幕中心的状态变化对象
        tencentMap.moveCamera(CameraUpdateFactory.newLatLng(nowLatLng));
        //now_marker = tencentMap.addMarker(new MarkerOptions(nowLatLng));

    }

    @Override
    public void onStatusUpdate(String s, int i, String s1) {

    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //可在此继续其他操作。
    }
    private void requirePermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            String[] permissions = {
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.READ_PHONE_STATE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
            };

            if (checkSelfPermission(mContext,permissions[0]) != PackageManager.PERMISSION_GRANTED)
            {
                requestPermissions(permissions, 0);
            }
        }
    }

    private Handler uiHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case -1:
                    //网络请求失败
                    Toast.makeText(mContext, "网络请求失败！", Toast.LENGTH_SHORT).show();
                    break;
                case 0:
                    //网络请求成功，但是返回状态为失败
                    Toast.makeText(mContext, msg.obj == null ? "获取商店数据失败！" : msg.obj.toString(), Toast.LENGTH_SHORT).show();
                    break;
                case 2:
                    showPoint();
                    break;
                default:
                    break;
            }

        }
    };
    /**
     * 获取步行导航规划
     */
    private void getWalkingRoute(){
        WalkingParam walkingParam = new WalkingParam();
        walkingParam.from(fromPoint);
        walkingParam.to(toPoint);
        TencentSearch tencentSearch = new TencentSearch(mContext);
        Log.i("TAG", "checkParams:" + walkingParam.checkParams());
        tencentSearch.getRoutePlan(walkingParam, new HttpResponseListener<WalkingResultObject>() {
            @Override
            public void onSuccess(int statusCode, WalkingResultObject object) {
                if (object == null) {
                    Log.i("TAG", "baseObject为空");
                    return;
                }
                showWalkingRoute(object);
                Log.i("TAG", "message:" + object.message);
            }

            @Override
            public void onFailure(int statusCode, String responseString, Throwable throwable) {
                Log.i("TAG:" ,statusCode + "  " + responseString);
            }
        });
    }

    private void showWalkingRoute(WalkingResultObject object) {
        tencentMap.clearAllOverlays();
        getLocation();
        if (object.result != null && object.result.routes != null && object.result.routes.size() > 0) {
            for (int i=0; i<object.result.routes.size(); i++) {
                WalkingResultObject.Route result = object.result.routes.get(i);
                tencentMap.addPolyline(new PolylineOptions().addAll(result.polyline).color(i+1).width(20));
                tencentMap.moveCamera(CameraUpdateFactory.newLatLngBounds(LatLngBounds.builder()
                        .include(result.polyline).build(), 100));

            }

        } else {
            Log.i("TAG", "没有找到适合的路线结果");
        }
    }

    private void getDrivingRoute(){
        DrivingParam drivingParam = new DrivingParam(fromPoint, toPoint); //创建导航参数

        drivingParam.roadType(DrivingParam.RoadType.ON_MAIN_ROAD_BELOW_BRIDGE);
        drivingParam.heading(90);
        drivingParam.accuracy(30);
        TencentSearch tencentSearch = new TencentSearch(mContext);
        tencentSearch.getRoutePlan(drivingParam, new HttpResponseListener<DrivingResultObject>() {

            @Override
            public void onSuccess(int i, DrivingResultObject drivingResultObject) {
                if (drivingResultObject == null){
                    return;
                }
                for (DrivingResultObject.Route route : drivingResultObject.result.routes){
                    List<LatLng> lines = route.polyline;
                    tencentMap.addPolyline(new PolylineOptions().addAll(lines).color(0x22ff0000));
                }
            }

            @Override
            public void onFailure(int i, String s, Throwable throwable) {

            }
        });
    }
}